<?php

/**
 * @Desc 成功返回
 * @param array|int|string $data
 * @param string $msg
 * @author yashuai<1762910894@qq.com>
 */
if (!function_exists('_success')) {
    function _success($data = [], string $msg = 'success')
    {
        return response()->json([
            "code" => 200,
            "msg"  => $msg,
            "result" => $data
        ]);
    }
}

/**
 * @Desc   失败返回
 * @param array $data
 * @param string $msg
 * @author yashuai<1762910894@qq.com>
 */
if (!function_exists('_fail')) {
    function _fail(int $code = 404, string $msg = '', array $data = [])
    {
        if (empty($msg)) {
            $msg = \HugCode\PhpUnits\Frame\Code\ResponseCode::CodeGetMsg($code);
            if (empty($msg)) {
                $msg = 'fail';
            }
        }

        return response()->json([
            "code"   => $code,
            "msg"    => $msg,
            "result" => $data,
        ])->header('errmsg', $msg);
    }
}

/**
 * @Desc 失败抛出异常
 * @param int $code
 * @param array $data
 * @param string $msg
 * @author yashuai<1762910894@qq.com>
 */
if (!function_exists('_throw')) {
    function _throw(string $msg = 'fail', int $code = 500)
    {
        throw new \App\Exceptions\ThrowException($msg, $code);
    }
}


/**
 * @Desc   获取当前控制器、方法名
 * @return array
 * @author yashuai<1762910894@qq.com>
 */
if (!function_exists('_controller_action')) {
    function _controller_action()
    {
        $router = request()->route()->getActionName();
        if (strpos($router, '@') === false) {
            return ['error', ''];
        }
        $router = array_slice(explode('\\', $router), -1, 1)[0];
        [$controller, $action] = explode('@', $router);
        $controller = str_replace('Controller', '', $controller);
        return [_to_under_score($controller), _to_under_score($action)];
    }
}


